package com.example.myapplication.service;

import static android.content.ContentValues.TAG;

import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;
import com.example.myapplication.bean.Inspection;
import com.example.myapplication.bean.Response;
import com.example.myapplication.util.HttpUtils;
import com.example.myapplication.util.StringUtils;
import com.example.myapplication.util.TableUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class InspectionService {
    private static final String URL = "http://101.43.110.183:8080/inspection";

    public ArrayList<ArrayList<String>> getInspections(String time, String classes, String category) {
        HashMap<String, String> params = new HashMap<>();
        if (!StringUtils.isEmpty(time)) {
            params.put("time", time);
        }
        if (!StringUtils.isEmpty(classes)) {
            params.put("classes", classes);
        }
        if (!StringUtils.isEmpty(category)) {
            params.put("category", category);
        }
        String responseInspectionJSONData = HttpUtils.get(URL, params);
        Gson gson = new Gson();
        Type typeJson = new TypeToken<Response<List<Inspection>>>() {
        }.getType();
        Response<List<Inspection>> response = gson.fromJson(responseInspectionJSONData, typeJson);
        if (response != null && response.getCode() == 200) {
            List<Inspection> inspectionList = response.getData();
            Collections.sort(inspectionList, (i1, i2) -> {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH : MM");
                try {
                    Date date1 = format.parse(i1.getTime());
                    Date date2 = format.parse(i2.getTime());
                    return date2.compareTo(date1);
                } catch (ParseException e) {
                    Log.e(TAG, "getTasks: Task date format error!", e);
                }
                return 0;
            });
            return TableUtils.convertObjectListToStringLists(inspectionList,true, "日期", "班次", "设备类别", "设备名称", "作业班组", "点检人",
                    "点检异常情况", "点检项目情况");
        }
        return null;
    }

    public Integer addInspection(Inspection inspection) {
        String  responseJson = HttpUtils.post(URL, inspection);
        Gson gson = new Gson();
        Response<Object> response = gson.fromJson(responseJson, new TypeToken<Response<Object>>() {
        }.getType());
        return response.getCode();
    }


    public List<String> getSelectedInspection() {
        return null;
    }

    public String getInspectionJSONString(String selectParams) {
        return null;
    }

}


